package mapreduce;

import java.util.Comparator;

public class RecordDefaultComparator implements Comparator<Record>{

	public int compare(Record record1, Record record2) {
		if(record1 == null || record2 == null){
			if(record1 == null && record2 != null){
				return 1;
			}
			if(record1 != null && record2 == null){
				return -1;
			}
			if(record1 == null && record2 == null){
				return 0;
			}
		}
		byte[] bytes1 = record1.getBytes();
		byte[] bytes2 = record2.getBytes();
		int valueComp = compare(bytes1, bytes2);
		return valueComp;
	}
	
	public int compareKey(Record record1, Record record2){
		return compare(record1.getKeyBytes(), record2.getKeyBytes());
	}
	
	public int compare(byte[] bytes1, byte[] bytes2){
		if(bytes1 == null || bytes2 == null){
			if(bytes1 == null && bytes2 != null){
				return 1;
			}
			else if(bytes1 != null && bytes2 == null){
				return -1;
			}
			else{
				return 0;
			}
		}
		int length1 = bytes1.length;
		int length2 = bytes2.length;
		int length = Math.min(length1, length2);
		for(int i = 0; i < length; i ++){
			byte b1 = bytes1[i];
			byte b2 = bytes2[i];
			if(b1 != b2){
				int cmp = getInt(b1) - getInt(b2);
				return cmp;
			}
		}
		return length1 - length2;
	}

	int getInt(byte b){
		int value = (int)b;
		if(value < 0){
			value = 256 + value;
		}
		return value;
	}
}
